package com.future.hedongjun.mine.fragment;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.future.baselib.entity.BaseResponse;
import com.future.baselib.http.HttpRequest;
import com.future.hedongjun.R;
import com.future.hedongjun.common.MyApp;
import com.future.hedongjun.home.bean.ThemeBean;
import com.future.hedongjun.mine.adapter.CachedAdapter;
import com.future.hedongjun.mine.bean.FileBean;
import com.future.hedongjun.mine.bean.FileType;
import com.future.hedongjun.mine.ui.ClassCacheActivity;
import com.future.hedongjun.mine.ui.FreeVideoActivity;
import com.future.hedongjun.mine.utils.FileUtil;
import com.kingsoft.media.httpcache.KSYProxyService;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class VideoFragment extends android.support.v4.app.Fragment {


    @BindView(R.id.cached_list)
    ListView lvCacheList;
    private KSYProxyService proxy;
    private CachedAdapter adapter;
    Unbinder unbinder;
    private List<FileBean> beanList = new ArrayList<>();
    private TextView tvBack;
    private String fileVideo;
    private ClassCacheActivity mContent;
    private String[] split;

    public VideoFragment() {
    }

    @SuppressLint("ValidFragment")
    public VideoFragment(TextView back, ClassCacheActivity context) {
        this.tvBack = back;
        this.mContent = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_video, container, false);
        unbinder = ButterKnife.bind(this, view);
        getData();

        return view;
    }


    public void getData() {
        proxy = MyApp.getKSYProxy(getActivity());
        proxy.startServer();
        adapter = new CachedAdapter(getActivity(), proxy);
        lvCacheList.setAdapter(adapter);
        fileVideo = Environment.getExternalStorageDirectory().toString() + File.separator + "CacheFile" + "/" + "CacheVideo";
        getFile(fileVideo);
        lvCacheList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                MyApp.isFlag = true;
                FileBean file = beanList.get(position);
                FileType fileType = file.getFileType();
                if (fileType == FileType.directory) {
                    getChildFile(file.getPath());
                } else {
                    Intent ToFree = new Intent(getContext(), FreeVideoActivity.class);
                    ToFree.putExtra("VideoUrl", beanList.get(position).getPath());
                    ToFree.putExtra("VideoName", beanList.get(position).getName());
                    startActivity(ToFree);
                }
            }
        });
    }

    private void getChildFile(String path) {
        File ChildRootFile = new File(path + File.separator);
        new ChildMyTask(ChildRootFile).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
    }

    public void getFile(String path) {
        File rootFile = new File(path + File.separator);
        new MyTask(rootFile).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
    }

    public void refresh() {
        adapter.cleanData();
        getFile(fileVideo);
    }

    @SuppressLint("StaticFieldLeak")
    class ChildMyTask extends AsyncTask {
        File file;

        ChildMyTask(File file) {
            this.file = file;
        }

        @Override
        protected Object doInBackground(Object[] params) {
            List<FileBean> fileBeenList = new ArrayList<>();
            Iterator iter = proxy.getCachedFileList().entrySet().iterator();
            while (iter.hasNext()) {
                FileBean myVideo = new FileBean();
                Map.Entry entry = (Map.Entry) iter.next();
                String url = (String) entry.getKey();
                File file = (File) entry.getValue();
                String path = file.getAbsolutePath();
                myVideo.setUrl(url);
                myVideo.setPath(path);
                myVideo.setName(url.substring(url.lastIndexOf('/') + 1));
                String urlName = url.substring(url.lastIndexOf('/') + 1);
                if (urlName.contains("mp4") && FileUtil.fileIsExists(path)) {
                    fileBeenList.add(myVideo);
                }
            }
            beanList = fileBeenList;
            return fileBeenList;
        }

        @Override
        protected void onPostExecute(Object o) {
            adapter.cleanData();
            adapter.addData(beanList);
        }
    }

    @SuppressLint("StaticFieldLeak")
    class MyTask extends AsyncTask {
        File file;

        MyTask(File file) {
            this.file = file;
        }

        @Override
        protected Object doInBackground(Object[] params) {
            List<FileBean> fileBeenList = new ArrayList<>();
            if (file.isDirectory()) {
                File[] filesArray = file.listFiles();
                if (filesArray != null) {
                    List<File> fileList = new ArrayList<>();
                    Collections.addAll(fileList, filesArray);  //把数组转化成list
                    Collections.sort(fileList, FileUtil.comparator);  //按照名字排序
                    for (File f : fileList) {
                        if (f.isHidden())
                            continue;
                        FileBean fileBean = new FileBean();
//                        if (themeBeanList!=null) {
//                            for (int i = 0; i < themeBeanList.size(); i++) {
//                                if (themeBeanList.get(i).t.name!=null&&!TextUtils.isEmpty(f.getName())) {
//                                    if (themeBeanList.get(i).t.name.equals(f.getName())) {
//                                        fileBean.setClassLogo(themeBeanList.get(i).t.getLogo_img());
//                                    }
//                                }
//
//                            }
//                        }
                        if (!TextUtils.isEmpty(f.getName())) {
                            split = f.getName().split("####");
                        }
                        fileBean.setName(split[0]);
                        fileBean.setPath(f.getAbsolutePath());
                        fileBean.setFileType(FileUtil.getFileType(f));
                        fileBean.setChildCount(FileUtil.getFileChildCount(f));
                        fileBean.setSize(f.length());
                        fileBean.setHolderType(0);
                        if (FileUtil.getFileChildCount(f) > 0) {
                            fileBeenList.add(fileBean);
                        }
                        if (split.length == 2) {
                            fileBean.setClassLogo(split[1]);
                        }
                    }
                }
            }
            beanList = fileBeenList;
            return fileBeenList;
        }

        @Override
        protected void onPostExecute(Object o) {
            //adapter.cleanData();
            adapter.addData(beanList);
        }
    }
}
